package com.cnoja.jmsncn.command;

import java.util.Arrays;

import com.cnoja.jmsncn.inf.IResponse;
import com.cnoja.jmsncn.kernel.ErrorCodes;
import com.cnoja.jmsncn.kernel.exceptions.CommandValidateException;
import com.cnoja.jmsncn.utils.command.CommandUtils;
import com.cnoja.jmsncn.utils.text.StringUtils;

public class DefaultCommand extends AbstractCommand {

	public DefaultCommand(String commandString) {
		super(commandString);
	}

	protected void validateLength(String[] array, int minimum, int maximum)
			throws CommandValidateException {

		if (minimum > 0 && array.length < minimum) {
			throw new CommandValidateException("The response must contain "
					+ minimum + " or parameters or above.");
		}
		if (maximum > 0 && array.length > maximum) {
			throw new CommandValidateException(
					"The response must contain elements lower to " + maximum);
		}
	}

	protected void validateContains(String[] split, String toSearch)
			throws CommandValidateException {
		if (Arrays.binarySearch(split, toSearch) < -1) {
			throw new CommandValidateException(
					"The response contains invalid protocol version:"
							+ split[2]);
		}
	}

	@Override
	public void validateResponse(IResponse response)
			throws CommandValidateException {
		if (this.hasResponse()) {
			if (StringUtils.notNullOrEmpty(response.getResponseContent())) {
				String[] split = CommandUtils.split(response
						.getResponseContent());
				if (split.length < 2) {
					throw new CommandValidateException(
							"The content is illegal.");

				} else if (split[0].trim().matches("\\d+")) {
					throw new CommandValidateException(
							"The command execution has failed ,the reason is ("+split[0].trim()+"),\""+ErrorCodes.getErrorMessage(split[0].trim())+"\"");
				}
			}else{
				throw new CommandValidateException("The response content is empty!");
			}

		}
		// TODO Auto-generated method stub
		super.validateResponse(response);
	}
}
